// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package securitycenter_test

import (
	"context"
	"fmt"
	"testing"

	"github.com/hashicorp/go-azure-helpers/lang/pointer"
	"github.com/hashicorp/go-azure-helpers/resourcemanager/commonids"
	"github.com/hashicorp/go-azure-sdk/resource-manager/security/2023-05-01/servervulnerabilityassessmentssettings"
	"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance"
	"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check"
	"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
	"github.com/hashicorp/terraform-provider-azurerm/internal/services/securitycenter/parse"
	"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
)

type SecurityCenterServerVulnerabilityAssessmentsSettingResource struct{}

func TestAccSecurityCenterVulnerabilityAssessmentsSetting_basic(t *testing.T) {
	data := acceptance.BuildTestData(t, "azurerm_security_center_server_vulnerability_assessments_setting", "test")
	r := SecurityCenterServerVulnerabilityAssessmentsSettingResource{}

	data.ResourceSequentialTest(t, r, []acceptance.TestStep{
		{
			Config: r.basicCfg("MdeTvm"),
			Check: acceptance.ComposeTestCheckFunc(
				check.That(data.ResourceName).ExistsInAzure(r),
			),
		},
		data.ImportStep(),
	})
}

func (SecurityCenterServerVulnerabilityAssessmentsSettingResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) {
	id, err := parse.VulnerabilityAssessmentsSettingID(state.ID)
	if err != nil {
		return nil, err
	}

	resp, err := clients.SecurityCenter.ServerVulnerabilityAssessmentSettingClient.Get(ctx, commonids.NewSubscriptionID(id.SubscriptionId))
	if err != nil {
		return nil, fmt.Errorf("checking for presence of existing %s: %v", id, err)
	}

	if resp.Model == nil {
		return pointer.To(false), nil
	}

	if azureServersSetting, ok := resp.Model.(servervulnerabilityassessmentssettings.AzureServersSetting); ok {
		if azureServersSetting.Properties == nil {
			return pointer.To(false), nil
		}
		if azureServersSetting.Properties.SelectedProvider != "" {
			return pointer.To(true), nil
		}
	}

	return pointer.To(false), nil
}

func (SecurityCenterServerVulnerabilityAssessmentsSettingResource) basicCfg(providerName string) string {
	return fmt.Sprintf(`
provider "azurerm" {
  features {}
}

resource "azurerm_security_center_subscription_pricing" "test" {
  tier          = "Standard"
  resource_type = "VirtualMachines"
  subplan       = "P2"
}


resource "azurerm_security_center_server_vulnerability_assessments_setting" "test" {
  vulnerability_assessment_provider = "%s"

  depends_on = [azurerm_security_center_subscription_pricing.test]
}
`, providerName)
}
